﻿using B.WMS.GoodsDto.Output;
using B.WMS.InWareHouseManagement;
using B.WMS.InWareHouseManagementDtos;
using B.WMS.IWMSService.Standing__Book;
using B.WMS.StandardReturn;
using B.WMS.WMSDtos.Inventory.Input;
using B.WMS.WMSDtos.Inventory.OutPut;
using B.WMS.WMSEntities.GoodsEntities;
using B.WMS.WMSEntities.Warehousety;
using MD5Hash;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net.WebSockets;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using static Plotly.NET.StyleParam.LinearAxisId;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace B.WMS.WMSService.Standing__Book
{
    public class Standing__BookAppService : ApplicationService, IStanding__BookAppService
    {
        /// <summary>
        /// 货品
        /// </summary>
        private readonly IRepository<Goods, Guid> _goodsRepo;
        /// <summary>
        /// 仓库
        /// </summary>
        private readonly IRepository<Warehouse, Guid> _warehouseRepo;
        /// <summary>
        /// 库位
        /// </summary>
        private readonly IRepository<Location, Guid> _locationRepo;
        private readonly IRepository<Units, Guid> _unitsRepository;
        private readonly IRepository<Goodstype, Guid> _goodstypeRepository;
        private readonly IRepository<InWareHouseModel, Guid> _wareHouseRepository;
        private readonly IRepository<IOWareHouseRecordModel, Guid> _iowareHouseRepository;
        private readonly IRepository<OutWareHouseModel, Guid> _outwareHouseRepository;
        private readonly IRepository<WVendor, Guid> _wvendorRepository;

        public Standing__BookAppService(IRepository<Goods, Guid> goodsRepo, IRepository<Warehouse, Guid> warehouseRepo, IRepository<Location, Guid> locationRepo, IRepository<InWareHouseModel, Guid> wareHouseRepository, IRepository<Goodstype, Guid> goodstypeRepository, IRepository<Units, Guid> unitsRepository, IRepository<IOWareHouseRecordModel, Guid> iowareHouseRepository, IRepository<OutWareHouseModel, Guid> outwareHouseRepository, IRepository<WVendor, Guid> wvendorRepository)
        {
            _goodsRepo = goodsRepo;
            _warehouseRepo = warehouseRepo;
            _locationRepo = locationRepo;
            _wareHouseRepository = wareHouseRepository;
            _goodstypeRepository = goodstypeRepository;
            _unitsRepository = unitsRepository;
            _iowareHouseRepository = iowareHouseRepository;
            _outwareHouseRepository = outwareHouseRepository;
            _wvendorRepository = wvendorRepository;
        }
        /// <summary>
        /// 库存查询
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<InventoryOutPut>> GetInventory(SearchInventoryInput input)
        {
            //出库表
            var ourwarehouse = await _outwareHouseRepository.GetQueryableAsync();
            //货品表
            var goods = await _goodsRepo.GetQueryableAsync();
            //待入库
            var goods1 = goods.Where(x => x.Goodsstatus == 1 && x.IsDelete == false);
            int waitincount = goods1.Count();
            //已入库
            var goods2 = goods.Where(x => x.Goodsstatus == 2 && x.IsDelete == false);
            int incount = goods2.Count();
            //待出库
            var ourwarehouse1 = ourwarehouse.Where(x => x.Status == 1);
            int waitoutcount = ourwarehouse1.Count();
            //已出库
            var ourwarehouse2 = ourwarehouse.Where(x => x.Status == 2);
            int outcount = ourwarehouse2.Count();
            var unit = await _unitsRepository.GetQueryableAsync();
            var type = await _goodstypeRepository.GetQueryableAsync();
            //仓库表
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            // //库位表
            var location = await _locationRepo.GetQueryableAsync();
            //入库表
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            inventory = inventory.Where(x => x.Status == 2);
            int sumnum = 0;
            decimal sunnummoney = 0;
            var query = from a in goods
                        join b in unit on a.GoodsUnitId equals b.Unitscoding
                        join c in type on a.Goodstypeid equals c.Goodstypecoding
                        join d in inventory on a.Goodscoding equals d.Relationordernum
                        join e in warehouse on d.WarehouseId equals e.WarehouseNo
                        join f in location on d.LocationNo equals f.LocationNo
                        select new InventoryOutPut
                        {
                            GoodsUnitId = b.Unitscoding,
                            Goodsbarcodes = a.Goodsbarcodes,
                            Goodscoding = a.Goodscoding,
                            Goodsname = a.Goodsname,
                            Goodsstatus = a.Goodsstatus,
                            WGoodscoding = a.Goodstypeid,
                            WGoodstypename = c.WGoodstypename,
                            Goodsspecifications = a.Goodsspecifications,
                            Num=a.Num,
                            LocationName = f.LocationName,
                            Warename = e.Warename,
                            UnitName = b.UnitName,
                            WaitSumInNum = waitincount,
                            SumInNum = incount,
                            WaitSumOutNum = waitoutcount,
                            SumNum = sumnum,
                            SumMoney = sunnummoney,
                            SumOutNum = outcount,
                            Storageprice=a.Storageprice,
                            Inventoryprice=a.Storageprice*a.Num,
                        };
            foreach (var item in query)
            {
                //入库
                if (item.Goodsstatus == 2)
                {
                    sumnum += item.Num;
                    sunnummoney += item.Storageprice * item.Num;
                }
                if (item.Goodsstatus == 3)
                {
                    sumnum -= item.Num;
                    sunnummoney -= item.Storageprice * item.Num;
                }
            }
            // 第二步：ToList() 后在内存中处理
            var listdata = query.ToList().Select(x => new InventoryOutPut
            {
                GoodsUnitId = x.GoodsUnitId,
                Goodsbarcodes = x.Goodsbarcodes,
                Goodscoding = x.Goodscoding,
                Goodsname = x.Goodsname,
                Goodsstatus = x.Goodsstatus,
                WGoodscoding = x.WGoodscoding,
                WGoodstypename = x.WGoodstypename,
                Goodsspecifications = x.Goodsspecifications,
                 Num = x.Num,
                Inventoryprice = x.Inventoryprice,
                LocationName = x.LocationName,
                Warename = x.Warename,
                UnitName = x.UnitName,
                WaitSumInNum = waitincount, // 这里可以用本地变量
                SumInNum = incount,
                WaitSumOutNum = waitoutcount,
                SumNum = sumnum,
                SumMoney = sunnummoney,
                SumOutNum = outcount,
            });
            if (!string.IsNullOrEmpty(input.Goodsname))
            {
                listdata = listdata.Where(a => a.Goodsname.Contains(input.Goodsname));
            }
            if (!string.IsNullOrEmpty(input.WGoodstypename))
            {
                listdata = listdata.Where(a => a.WGoodstypename.Contains(input.WGoodstypename));
            }
            if (!string.IsNullOrEmpty(input.Warename))
            {
                listdata = listdata.Where(a => a.Warename.Contains(input.Warename));
            }
            if (!string.IsNullOrEmpty(input.UnitName))
            {
                listdata = listdata.Where(a => a.UnitName.Contains(input.UnitName));
            }
            if (!string.IsNullOrEmpty(input.Goodsbarcodes))
            {
                listdata = listdata.Where(a => a.Goodsbarcodes.Contains(input.Goodsbarcodes));
            }
            var count = listdata.Count();
            var list = listdata.OrderByDescending(x => x.Goodscoding).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            return new ApiPaging<InventoryOutPut>()
            {
                TotalData = count,
                TotalPage = (count + input.PageSize - 1) / input.PageSize,
                PageDatas = list,
                Code = ApiCode.Success,
                Message = "获取成功"
            };
        }

        /// <summary>
        /// 出入库流水
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<Out_InWarehouseOutPut>> Out_InWarehouseOutPut(string? Goodscoding, int PageIndex, int PageSize, string? Warename, string? Out_InType, DateTime? Out_InTime)
        {
            var result = new ApiPaging<Out_InWarehouseOutPut>();
            //入出库记录
            var list = await _iowareHouseRepository.GetQueryableAsync();
          //出库
          var outlist = list.Where( x => x.Isdelete==false&&x.Status == 4&&  x.GoodsId == Goodscoding);
            //入库
            var inlist = list.Where(x => x.Isdelete == false && x.Status == 2&&x.GoodsId == Goodscoding);
            //货品表
            var goods = await _goodsRepo.GetQueryableAsync();
            //仓库表
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            //入库表
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            var query =
                from a in goods
                join d in inventory on a.Goodscoding equals d.Relationordernum
                join e in warehouse on d.WarehouseId equals e.WarehouseNo
                join c in inlist on a.Goodscoding equals c.GoodsId 
                join b in outlist on a.Goodscoding equals b.GoodsId into outGroup
                from outJoined in outGroup.DefaultIfEmpty()
                select new Out_InWarehouseOutPut
                {
                    GoodsId = a.Goodscoding,
                    Operationdate = d.Inwarehousedate,
                    Recordtype = a.Goodsstatus.ToString(),
                    Warename = e.Warename,
                    //入库数量
                    InNum = c.Num,
                    //出库数量
                    OutNum = outJoined.Num,
                    //入库金额
                    InMoney = c.Money,
                    //出库金额
                    OutMoney = outJoined.Money

                };
           
            if (!string.IsNullOrEmpty(Warename))
            {
                query = query.Where(x => x.Warename.Contains(Warename));
            }
            if (Out_InType != null)
            {
                query = query.Where(x => x.Recordtype == Out_InType);
            }
            if (Out_InTime != null)
            {
                query = query.Where(x => x.Operationdate >= Out_InTime&&x.Operationdate<Out_InTime.Value.AddDays(1));
            }
            var count = query.Count();
            var listpage = query.OrderByDescending(x => x.Operationdate).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            result.Code = ApiCode.Success;
            result.PageDatas = listpage;
            result.Message = "获取成功";
            result.TotalData = count;
            if(count!=0)
            {
                result.TotalPage = (count + PageIndex - 1) / PageSize;
            }
           
            return result;
        }
        
        /// <summary>
        /// 获取库存分布
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<Inventory_DistributionOutPut>>> GetInventory_Distribution(string GoodsId)
        {
            var goods = await _goodsRepo.GetQueryableAsync();
            goods = goods.Where(x => x.Goodscoding == GoodsId);
            // //仓库表
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            // //库位表
            var location = await _locationRepo.GetQueryableAsync();
            //入库表
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            var list1 = inventory.Where(x => x.Status == 1);
            var list2 = inventory.Where(x => x.Status == 2);
            int t1 = list1.Count();
            int t2 = list2.Count();

            var linq = from x in goods
                       join a in inventory on x.Goodscoding equals a.Relationordernum
                       join b in warehouse on a.WarehouseId equals b.WarehouseNo
                       join c in location on a.LocationNo equals c.LocationNo
                       select new Inventory_DistributionOutPut
                       {
                           // 仓库名称
                           Warename = b.Warename,
                           // 库位编号
                           LocationNo = c.LocationNo,
                           // 库位名称
                           LocationName = c.LocationName,
                           // 当前库存
                           Inventory = b.Wsorting,
                           // 可用库存
                           AvailableInventory = b.Wsorting,
                           //入库数量
                           InNum = t1,
                           //出库数量
                           OutNum = t2,
                       };
            var resultList = linq.ToList();

            var result = new ApiPaging<List<Inventory_DistributionOutPut>>();

            result.Code = ApiCode.Success;
            result.ResultData = linq.ToList();
            return result;
        }
        /// <summary>
        /// 获取数量
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<NumOutput>> GetNum(string GoodsId)
        {
            var list = GetInventory_Distribution(GoodsId);
            var goods = await _goodsRepo.GetQueryableAsync();
            goods = goods.Where(x => x.Goodscoding == GoodsId);
            // //仓库表
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            // //库位表
            var location = await _locationRepo.GetQueryableAsync();
            //入库表
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            var list1 = inventory.Where(x => x.Status == 1);
            var list2 = inventory.Where(x => x.Status == 2);
            int t1 = list1.Count();
            int t2 = list2.Count();

            var linq = from x in goods
                       join a in inventory on x.Goodscoding equals a.Relationordernum
                       join b in warehouse on a.WarehouseId equals b.WarehouseNo
                       join c in location on a.LocationNo equals c.LocationNo
                       select new { x, a, b, c };
            // 当前库存总数
            var sum1 = linq.Sum(x => x.b.Wsorting);
            var sum2 = linq.Sum(x => x.b.Wsorting);
            var sum3 = t1;
            var sum4 = t2;
            var result = new NumOutput
            {
                q1 = sum1,
                q2 = sum2,
                q3 = sum3,
                q4 = sum4
            };
            var result1 = new ApiResult<NumOutput>();
            result1.Code = ApiCode.Success;
            result1.ResultData = result;
            result1.Message = "获取成功";
            return result1;


        }
       /// <summary>
       /// 获取货品详情
       /// </summary>
       /// <param name="GoodsId"></param>
       /// <returns></returns>
       /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<GoodsOutput>> getGoods(string GoodsId)
        {
            var result=new ApiResult<GoodsOutput>();
            var goods = await _goodsRepo.GetListAsync();
            goods = goods.Where(x => x.Goodscoding == GoodsId).ToList();
            var unit = await _unitsRepository.GetListAsync();
            var type = await _goodstypeRepository.GetListAsync();
            var vendor = await _wvendorRepository.GetListAsync();

            var linq = from a in goods
                       join b in unit on a.GoodsUnitId equals b.Unitscoding
                       join c in type on a.Goodstypeid equals c.Goodstypecoding
                       join d in vendor on a.Vendorid equals d.WVendorcoding
                       select new GoodsOutput
                       {
                           Goodstypeid = a.GoodsUnitId,
                           GoodsUnitId = b.Unitscoding,
                           Createperson = a.Createperson,
                           Createtime = a.CreationTime,
                           Customerid = a.Customerid,
                           CustomerName = a.Customerid,
                           Earlywarning = a.Earlywarning,
                           Goodaimages = a.Goodaimages,
                           Goodsbarcodes = a.Goodsbarcodes,
                           Goodscoding = a.Goodscoding,
                           Goodsfile = a.Goodsfile,
                           Goodsname = a.Goodsname,
                           Goodsspecifications = a.Goodsspecifications,
                           Goodsstatus = a.Goodsstatus,
                           GoodstyoeName = c.WGoodstypename,
                           GoodsUnitName = b.UnitName,
                           Num= a.Num,
                           Inventoryprice = a.Inventoryprice,
                           Retrievalprice = a.Retrievalprice,
                           Shelflife = a.Shelflife,
                           Storageprice = a.Storageprice,
                           Updatetime = a.Updatetime,
                           Vendorid = a.Vendorid,
                           VendorName = d.WVendorname,
                           ProductionTime = a.ProductionTime,
                       };

            result.Code = ApiCode.Success;
            result.ResultData = linq.FirstOrDefault();
            return result;
        }
        /// <summary>
        /// 获取仓库下拉框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<SelectWareHouseDto>>> GetSelectWareHouse()
        {
            var wareList = await _warehouseRepo.GetListAsync();
            var dtoList = ObjectMapper.Map<List<Warehouse>, List<SelectWareHouseDto>>(wareList);
            return new ApiResult<List<SelectWareHouseDto>>
            {
                Code = ApiCode.Success,
                Message = "获取成功",
                ResultData = dtoList
            };
        }
        /// <summary>
        /// 保质期
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<GetgoodsTimeDTO>> GetGoodsTimes(SearchGoodsTimesDTO input)
        {
            // 1. 获取各表查询对象（保持不变）
            var goods = await _goodsRepo.GetQueryableAsync();
            var unit = await _unitsRepository.GetQueryableAsync();
            var type = await _goodstypeRepository.GetQueryableAsync();
            var vendors = await _wvendorRepository.GetQueryableAsync();
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            var location = await _locationRepo.GetQueryableAsync();

            // 2. 基础查询（仅获取原始数据，不做计算）
            var baseQuery = from a in goods
                            join b in unit on a.GoodsUnitId equals b.Unitscoding
                            join c in type on a.Goodstypeid equals c.Goodstypecoding
                            join g in vendors on a.Vendorid equals g.WVendorcoding
                            join d in inventory on a.Goodscoding equals d.Relationordernum
                            join e in warehouse on d.WarehouseId equals e.WarehouseNo
                            join f in location on d.LocationNo equals f.LocationNo
                            select new
                            {
                                Goods = a,
                                Unit = b,
                                Type = c,
                                Vendor = g,
                                Inventory = d,
                                Warehouse = e,
                                Location = f
                            };

            // 3. 过滤条件（修复所有类型转换问题）
            // 3.1 按商品名称过滤（字符串包含，正常支持）
            if (!string.IsNullOrEmpty(input.Goodsname))
            {
                baseQuery = baseQuery.Where(x => x.Goods.Goodsname.Contains(input.Goodsname));
            }

            // 3.2 按商品类型ID过滤（修复 ToString() 问题）
            if (!string.IsNullOrEmpty(input.GoodstyoeName))
            {
                // 将输入字符串转换为 Goodstypeid 的类型（假设是 int）
                baseQuery = baseQuery.Where(x => x.Goods.Goodstypeid == input.GoodstyoeName);
            }

            // 3.3 按单位ID过滤（同类型转换逻辑）
            if (!string.IsNullOrEmpty(input.GoodsUnitName))
            {
                // 假设 GoodsUnitId 是 int 类型，转换输入为 int
                baseQuery = baseQuery.Where(x => x.Goods.GoodsUnitId == input.GoodsUnitName);
            }

            // 3.4 按商品条码过滤（正常支持）
            if (!string.IsNullOrEmpty(input.Goodsbarcodes))
            {
                baseQuery = baseQuery.Where(x => x.Goods.Goodsbarcodes.Contains(input.Goodsbarcodes));
            }

            // 3.5 按仓库编号过滤（正常支持）
            if (!string.IsNullOrEmpty(input.WarehouseNo))
            {
                baseQuery = baseQuery.Where(x => x.Warehouse.WarehouseNo == input.WarehouseNo);
            }

            // 4. 执行分页查询（先排序、分页，再取数据，减少内存占用）
            var totalCount = baseQuery.Count(); // 总条数（数据库层面计算）

            var queryResult = baseQuery
                .OrderByDescending(x => x.Goods.ProductionTime) // 排序
                .Skip((input.PageIndex - 1) * input.PageSize)   // 分页：跳过前面的页
                .Take(input.PageSize)                           // 分页：取当前页数据
                .ToList();                                 // 异步执行查询（关键：避免同步 ToList()）

            // 5. 在内存中处理 Days 和 Status（避免数据库层面计算）
            var list = queryResult.Select(x =>
            {
                // 计算剩余天数（生产日期 + 保质期 - 当前时间）
                var expireDate = x.Goods.ProductionTime.AddMonths(x.Goods.Shelflife);
                var days = (int)(expireDate - DateTime.Now).TotalDays;

                // 确定状态
                var status = days < 0 ? "已过期" : (days < 7 ? "即将过期" : "正常");

                // 封装返回DTO
                return new GetgoodsTimeDTO
                {
                    GoodsUnitId = x.Unit.Unitscoding,
                    Goodsbarcodes = x.Goods.Goodsbarcodes,
                    Goodscoding = x.Goods.Goodscoding,
                    Goodsname = x.Goods.Goodsname,
                    Goodsstatus = x.Goods.Goodsstatus,
                    Goodstypeid = x.Goods.Goodstypeid,
                    GoodstyoeName = x.Type.WGoodstypename,
                    Goodsspecifications = x.Goods.Goodsspecifications,
                    Num = x.Goods.Num,
                    Inventoryprice = x.Goods.Inventoryprice,
                    LocationName = x.Location.LocationName,
                    Warename = x.Warehouse.Warename,
                    GoodsUnitName = x.Unit.UnitName,
                    Shelflife = x.Goods.Shelflife,
                    Goodsfile = x.Goods.Goodsfile,
                    Earlywarning = x.Goods.Earlywarning,
                    ProductionTime = x.Goods.ProductionTime,
                    Days = days,
                    Customerid = x.Goods.Customerid,
                    Vendorid = x.Goods.Vendorid,
                    VendorName = x.Vendor.WVendorname,
                    Status = status,

                };
            }).ToList();

            // 6. 对内存中的结果应用剩余过滤（Days和Status是内存计算的，需在内存中过滤）
            if (input.nums1 != null && input.nums2 != null)
            {
                list = list.Where(a => a.Days >= input.nums1 && a.Days <= input.nums2).ToList();
            }
            if (input.Status != null)
            {
                list = list.Where(a => a.Status == input.Status).ToList();
            }

            // 7. 返回分页结果
            return new ApiPaging<GetgoodsTimeDTO>
            {
                TotalData = totalCount,
                TotalPage = (totalCount + input.PageSize - 1) / input.PageSize,
                PageDatas = list,
                Code = ApiCode.Success,
                Message = "获取成功"
            };
        }
        /// <summary>
        /// 获取商品批次
        /// </summary>
        /// <param name="dTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<piciDTO>> Getpici(SearchpiciInput dTO)
        {
            var result = new ApiPaging<piciDTO>();
            var goods = await _goodsRepo.GetListAsync();
            var unit = await _unitsRepository.GetListAsync();
            var type = await _goodstypeRepository.GetListAsync();
            //仓库表
            var warehouse = await _warehouseRepo.GetQueryableAsync();
            // //库位表
            var location = await _locationRepo.GetQueryableAsync();
            var inventory= await _wareHouseRepository.GetQueryableAsync();

            var linq = from a in goods
                       join b in unit on a.GoodsUnitId equals b.Unitscoding
                       join c in type on a.Goodstypeid equals c.Goodstypecoding
                       join d in inventory on a.Goodscoding equals d.Relationordernum
                       join e in warehouse on d.WarehouseId equals e.WarehouseNo
                       join f in location on d.LocationNo equals f.LocationNo
                       select new
                       {
                           goods = a,
                           unit = b,
                           type = c,
                           inventory = d,
                           warehouse = e,
                           location = f
                       };
            if(!string.IsNullOrEmpty(dTO.Goodsname))
            {
                linq = linq.Where(x => x.goods.Goodsname.Contains(dTO.Goodsname));
            }
            if (!string.IsNullOrEmpty(dTO.Goodstypeid))
            {
                linq = linq.Where(x=>x.type.Goodstypecoding==dTO.Goodstypeid);
            }
            if(!string.IsNullOrEmpty(dTO.GoodsUnitId))
            {
                linq = linq.Where(x => x.unit.Unitscoding == dTO.GoodsUnitId);
            }
            if (dTO.ProductionTime!=null)
            {
                linq = linq.Where(x => x.goods.ProductionTime >= dTO.ProductionTime && x.goods.ProductionTime < dTO.ProductionTime.Value.AddDays(1));
            }
            if (!string.IsNullOrEmpty(dTO.Warename))
            {
                linq = linq.Where(x => x.warehouse.WarehouseNo==dTO.Warename);
            }
            var list = linq.Select(x =>
            {
                //计算到期日期
                var enttimes=x.goods.ProductionTime.AddMonths(x.goods.Shelflife);
                //取中间的时间

                var pici=x.goods.Goodscoding.Substring(4,8);
                return new piciDTO
                {
                    GoodsUnitId = x.unit.Unitscoding,
                    Goodsbarcodes = x.goods.Goodsbarcodes,
                    Goodscoding = x.goods.Goodscoding,
                    Goodsname = x.goods.Goodsname,
                    Goodsstatus = x.goods.Goodsstatus,
                    Goodstypeid = x.goods.Goodstypeid,
                    GoodstyoeName = x.type.WGoodstypename,
                    Goodsspecifications = x.goods.Goodsspecifications,
                    LocationName = x.location.LocationName,
                    Warename = x.warehouse.Warename,
                    GoodsUnitName = x.unit.UnitName,
                    Shelflife = x.goods.Shelflife,
                    ProductionTime = x.goods.ProductionTime,
                    EndTimes = enttimes,
                    PiciCoding = pici,
                    Wsorting= x.warehouse.Wsorting,

                };
            }).ToList();
          if(dTO.EndTime!=null)
            {
                
                list = list.Where(x => x.EndTimes >= dTO.EndTime&&x.EndTimes<dTO.EndTime.Value.AddDays(1)).ToList();
            }
          if(!string.IsNullOrEmpty(dTO.PiciCoding))
            {
                list = list.Where(x => x.PiciCoding == dTO.PiciCoding).ToList();
            }
          result.Code= ApiCode.Success;
         result.PageDatas= list
                .OrderByDescending(x => x.Goodscoding)
                .Skip((dTO.PageIndex - 1) * dTO.PageSize)
                .Take(dTO.PageSize)
                .ToList();
            result.TotalData = list.Count();
            result.TotalPage = (result.TotalData + dTO.PageSize - 1) / dTO.PageSize;
            result.Message = "获取成功";
            return result;
        }
        /// <summary>
        /// 获取库存分布统计图
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<WarehouseOutInput>>> GetWaeHouse(int days=0)
        {
            

            var warehouse=await _warehouseRepo.GetQueryableAsync();
            //出库表
            var ourwarehouse = await _outwareHouseRepository.GetQueryableAsync();
            //货品表
            var goods = await _goodsRepo.GetQueryableAsync();
            //入库表
            var inventory = await _wareHouseRepository.GetQueryableAsync();
            inventory = inventory.Where(x => x.Status == 2);
            var query = from a in goods
                        join d in inventory on a.Goodscoding equals d.Relationordernum
                        join e in warehouse on d.WarehouseId equals e.WarehouseNo
                        select new WarehouseOutInput
                        {
                            Warename = e.Warename,
                            Inventory =a.Num,
                            SumMoney = a.Num*a.Storageprice,
                            Times = d.CreationTime
                        };
            
            // 第二步：ToList() 后在内存中处理
            var listdata = query.ToList().Select(x => new WarehouseOutInput
            {
                Warename = x.Warename,
                Inventory = x.Inventory,
                SumMoney = x.SumMoney,
                Times = x.Times
            });
            //按时间和仓库分组
            //是同一仓库统一时间的就累加
            var group = listdata.GroupBy(x => new
            { x.Warename,
            x.Times.Date
            });
            
            var results = group.Select(x => new WarehouseOutInput
            {
                Warename = x.Key.Warename,
                Times = x.Key.Date,
                Inventory = x.Sum(y => y.Inventory),
                SumMoney = x.Sum(y => y.SumMoney)
            });
            //判断如果是当天
            if(days!= null)
            {
                if (days == 0)
                {
                    var date = DateTime.Now.ToString("yyyy-MM-dd");
                    results = results.Where(x => x.Times.ToString("yyyy-MM-dd") == date);
                    var resultlist = new ApiResult<List<WarehouseOutInput>>
                    {
                        Code = ApiCode.Success,
                        Message = "获取成功",
                        ResultData = results.ToList()
                    };
                    return resultlist;
                }
                if (days ==1)
                {
                    var startTime1 = DateTime.Now.AddDays(-days).Date;
                   var  startTime2 = startTime1.ToString("yyyy-MM-dd");
                    results = results.Where(x => x.Times.ToString("yyyy-MM-dd") == startTime2);
                    var resultlist = new ApiResult<List<WarehouseOutInput>>
                    {
                        Code = ApiCode.Success,
                        Message = "获取成功",
                        ResultData = results.ToList()
                    };
                    return resultlist;
                }
                //先计算时间 分为昨天今天近一周和近一个月
                var startTime = DateTime.Now.AddDays(-days).Date;
                
                var endTime = DateTime.Now.Date;

                results = results.Where(x => x.Times >= startTime && x.Times < endTime.AddDays(1));
            }
            var result = new ApiResult<List<WarehouseOutInput>>
            {
                Code = ApiCode.Success,
                Message = "获取成功",
                ResultData = results.ToList()
            };
            return result;


        }

    }
}
